package com.shiliao.framework.base.annotation;

import android.app.Activity;

import com.shiliao.framework.YimeiFrameworkAppliction;
import com.shiliao.framework.util.LogUtil;

import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * Created by yjl on 2017/6/20.
 */

public class ThreadUtil {

    public static void getUIThread(final Class<?> clazz, final Object... params) throws ClassNotFoundException {
        Method[] methods = clazz.getDeclaredMethods();
        for (final Method method : methods) {
            if (method.isAnnotationPresent(YMSubscribe.class)) {
                YMSubscribe ymSubscribe = method.getAnnotation(YMSubscribe.class);
                if (YMThreadMode.POSTING.equals(ymSubscribe.threadMode())) {
                    Class<?> childActivity = ymSubscribe.type();
                    ArrayList<Activity> list = YimeiFrameworkAppliction.getInstance().getAllActivitys();

                    for (final Activity activity : list) {
                        LogUtil.e("yjl", "Activitty:" + activity.getClass().getSimpleName()
                                + "-----childActivity:" + childActivity.getSimpleName());
                        if (activity.getClass().equals(childActivity)) {
                            final WeakReference<Activity> weakReference = new WeakReference<Activity>(activity);
                            weakReference.get().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        method.invoke(activity, params);
                                    } catch (IllegalAccessException e) {
                                        e.printStackTrace();
                                    } catch (InvocationTargetException e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                        }
                    }
                }
            }

        }
    }


}
